package com.atlin.project.controller;

import com.atlin.project.annotation.AuthCheck;
import com.atlin.project.common.BaseResponse;
import com.atlin.project.common.DeleteRequest;
import com.atlin.project.common.ErrorCode;
import com.atlin.project.common.ResultUtils;
import com.atlin.project.contant.UserConstant;
import com.atlin.project.exception.BusinessException;
import com.atlin.project.exception.ThrowUtils;
import com.atlin.project.model.domain.BiTeam;
import com.atlin.project.model.domain.SysUser;
import com.atlin.project.model.domain.chart.Chart;
import com.atlin.project.model.dto.biTeam.BiJoinTeamRequest;
import com.atlin.project.model.dto.biTeam.BiTeamAddRequest;
import com.atlin.project.model.dto.biTeam.BiTeamQueryRequest;
import com.atlin.project.model.dto.biTeam.BiTeamUpdateRequest;
import com.atlin.project.model.vo.BiTeamVO;
import com.atlin.project.service.BiTeamService;
import com.atlin.project.service.BiUserTeamService;
import com.atlin.project.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Random;
import java.util.UUID;

/**
 * 团队接口
 *
 * @author atlin
 */
@RestController
@RequestMapping("/biTeam")
public class BiTeamController {

    @Resource
    private BiTeamService biTeamService;

    @Resource
    private BiUserTeamService biUserTeamService;

    @Resource
    private SysUserService sysUserService;

    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param biTeamAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addBiTeam(@RequestBody BiTeamAddRequest biTeamAddRequest, HttpServletRequest request) {
        if (biTeamAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        BiTeam biTeam = new BiTeam();
        Long chartId = biTeamAddRequest.getChartId();
        biTeam.setChartId(chartId);
        SysUser loginUser = sysUserService.getLoginUser(request);
        biTeam.setCreateUserId(loginUser.getId());
        biTeam.setJoinPassword(UUID.randomUUID().toString().substring(0, 6));
        biTeamService.valid(biTeam, true);

        LambdaQueryWrapper<BiTeam> wrapper = new LambdaQueryWrapper<BiTeam>().eq(BiTeam::getCreateUserId, loginUser.getId())
                .eq(BiTeam::getChartId, chartId);
        BiTeam oldBiTeam = biTeamService.getOne(wrapper);
        ThrowUtils.throwIf(oldBiTeam != null, ErrorCode.PARAMS_ERROR, "此团队已存在");

        boolean result = biTeamService.save(biTeam);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        long newBiTeamId = biTeam.getId();

        //存储成员信息
        result = biUserTeamService.saveUserTeam(loginUser.getId(), newBiTeamId);

        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(newBiTeamId);
    }


    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteBiTeam(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        SysUser user = sysUserService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        BiTeam oldbiTeam = biTeamService.getById(id);
        ThrowUtils.throwIf(oldbiTeam == null, ErrorCode.NULL_ERROR);

        // 仅本人或管理员可删除
        if (!oldbiTeam.getCreateUserId().equals(user.getId()) && !sysUserService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = biTeamService.disbandTeam(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param biTeamUpdateRequest
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateBiTeam(@RequestBody BiTeamUpdateRequest biTeamUpdateRequest, HttpServletRequest request) {
        if (biTeamUpdateRequest == null || biTeamUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        SysUser user = sysUserService.getLoginUser(request);

        BiTeam biTeam = new BiTeam();
        BeanUtils.copyProperties(biTeamUpdateRequest, biTeam);

        // 参数校验
        biTeamService.valid(biTeam, false);
        long id = biTeamUpdateRequest.getId();
        // 判断是否存在
        BiTeam oldbiTeam = biTeamService.getById(id);
        ThrowUtils.throwIf(oldbiTeam == null, ErrorCode.NULL_ERROR);

        // 仅本人或管理员可编辑
        if (!oldbiTeam.getCreateUserId().equals(user.getId()) && !sysUserService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        boolean result = biTeamService.updateById(biTeam);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<BiTeam> getBiTeamById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        BiTeam biTeam = biTeamService.getById(id);
        if (biTeam == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        SysUser loginUser = sysUserService.getLoginUser(request);
        // 不是本人或管理员，不能直接获取所有信息
        if (!biTeam.getCreateUserId().equals(loginUser.getId()) && !sysUserService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return ResultUtils.success(biTeam);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<BiTeamVO> getBiTeamVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        BiTeam biTeam = biTeamService.getById(id);
        if (biTeam == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }

        BiTeamVO biTeamVO = BiTeamVO.objToVo(biTeam);
        return ResultUtils.success(biTeamVO);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param biTeamQueryRequest 查询参数
     * @param request            查询请求
     * @return 分页封装类
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<BiTeamVO>> listBiTeamVOByPage(@RequestBody BiTeamQueryRequest biTeamQueryRequest,
                                                           HttpServletRequest request) {
        long current = biTeamQueryRequest.getCurrent();
        long size = biTeamQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<BiTeam> biTeamPage = biTeamService.page(new Page<>(current, size),
                biTeamService.getQueryWrapper(biTeamQueryRequest));

        Page<BiTeamVO> biTeamVOPage = biTeamService.getBiTeamVOPage(biTeamPage, request);

        return ResultUtils.success(biTeamVOPage);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param biTeamQueryRequest 查询参数
     * @param request            查询请求
     * @return 分页
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<BiTeam>> listBiTeamByPage(@RequestBody BiTeamQueryRequest biTeamQueryRequest,
                                                       HttpServletRequest request) {
        long current = biTeamQueryRequest.getCurrent();
        long size = biTeamQueryRequest.getPageSize();
        Page<BiTeam> biTeamPage = biTeamService.page(new Page<>(current, size),
                biTeamService.getQueryWrapper(biTeamQueryRequest));
        return ResultUtils.success(biTeamPage);
    }

    // endregion

    /**
     * 加入团队
     *
     * @param biJoinTeamRequest
     * @param request
     * @return
     */
    @PostMapping("/joinBiTeam")
    public BaseResponse<Boolean> joinBiTeam(@RequestBody BiJoinTeamRequest biJoinTeamRequest, HttpServletRequest request) {
        if (biJoinTeamRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long teamId = biJoinTeamRequest.getTeamId();
        SysUser loginUser = sysUserService.getLoginUser(request);

        BiTeam team = biTeamService.getById(teamId);
        ThrowUtils.throwIf(team == null, ErrorCode.PARAMS_ERROR, "此团队不存在");

        String joinPassword = biJoinTeamRequest.getJoinPassword();
        String successPwd = team.getJoinPassword();
        if (StringUtils.isNotBlank(successPwd) && !team.getJoinPassword().equals(joinPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }

        //存储成员信息
        boolean result = biUserTeamService.saveUserTeam(loginUser.getId(), teamId);

        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 离开团队
     *
     * @param biJoinTeamRequest
     * @param request
     * @return {@link BaseResponse<Boolean>}
     */
    @PostMapping("/leaveBiTeam")
    public BaseResponse<Boolean> leaveBiTeam(@RequestBody BiJoinTeamRequest biJoinTeamRequest, HttpServletRequest request) {
        if (biJoinTeamRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long teamId = biJoinTeamRequest.getTeamId();
        SysUser loginUser = sysUserService.getLoginUser(request);

        BiTeam team = biTeamService.getById(teamId);
        ThrowUtils.throwIf(team == null, ErrorCode.PARAMS_ERROR, "此团队不存在");

        //离开团队
        boolean result = biTeamService.leaveTeam(loginUser.getId(), teamId);

        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }
    

    @GetMapping("/shareBiTeam")
    public BaseResponse<BiTeamVO> shareBiTeam(long chartId, HttpServletRequest request) {
        if (chartId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        BiTeam biTeam = biTeamService.getTeamByChartId(chartId);
        if (biTeam == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }

        BiTeamVO biTeamVO = BiTeamVO.objToVo(biTeam);
        return ResultUtils.success(biTeamVO);
    }
}
